var contacts_rawDetailsSet = new Array();
var contacts_detailsPopup;
var contacts_confirmedData;

/*
 * Container, which creates and holds all the values from the raw contact.
 */
function contacts_RawDetails(_json) {
	// alert(debugObject(_json.availGroups));
	this.editables = new Array();
	this.simpleValue = function(_value) {
		var value = document.createElement("input");
		value.rawDetails = this;
		value.readOnly = true;
		value.type = "text";
		if (_value != null && _value.trim() != "") {
			value.value = _value;
		} else {
			value.value = _T("Empty");
			value.className = "empty";
		}
		this.editables.push(value);
		return value;
	}
	this.arrayValue = function(_values) {
		var values = document.createElement("span");
		if (_values != null && _values.length > 0) {
			for ( var i = 0; i < _values.length; i++) {
				var value = this.simpleValue(_values[i]);
				value.isArrayValue = true;
				values.appendChild(value);
			}
		} else {
			var value = this.simpleValue("");
			value.isArrayValue = true;
			values.appendChild(value);
		}
		return values;
	}

	this.predefinedValue = function(_values, _definitions) {
		definitions = _definitions.slice();
		var select = document.createElement("select");
		select.multiple = true;
		for ( var i = 0; i < definitions.length; i++) {
			for ( var j = 0; j < _values.length; j++) {
				if (_values[j] == definitions[i]) {
					var option = document.createElement("option");
					option.textContent = definitions[i];
					definitions[i] = null;
					option.selected = true;
					select.add(option);
				}
			}
		}
		for ( var i = 0; i < definitions.length; i++) {
			if (definitions[i] != null) {
				var option = document.createElement("option");
				option.textContent = definitions[i];
				select.add(option);
			}
		}
		select.disabled = true;
		this.editables.push(select);
		return select;
	}

	this.setEditable = function() {
		for ( var i = 0; i < this.editables.length; i++) {
			var element = this.editables[i];
			if (element.readOnly) {
				element.readOnly = false;
				element.setAttribute("onfocus", "contacts_startEdit(this);");
				element.setAttribute("onblur", "contacts_stopEdit(this);");
			}
			if (element.disabled) {
				element.disabled = false;
			}
		}
	}
	this.rawId = _json.idRaw;
	this.contactId = _json.idContact;
	this.deleted = _json.deleted;
	this.photo = document.createElement("img");
	this.photo.rawDetails = this;
	this.photo.className = "contactPhoto";
	if (_json.photo) {
		this.photo.setAttribute("src", "data:image/png;base64," + _json.photo);
	} else {
		this.photo.setAttribute("src", "/none.png");
	}
	this.accountName = document.createElement("div");
	this.accountName.textContent = _json.accountName;
	this.accountType = document.createElement("div");
	this.accountType.textContent = _json.accountType;
	this.name = this.simpleValue(_json.name);
	this.nick = this.simpleValue(_json.nick);
	this.groups = this.predefinedValue(_json.groups, _json.availGroups);
	this.emails = this.arrayValue(_json.emails);
	this.phones = this.arrayValue(_json.phones);
	this.sips = this.arrayValue(_json.sips);
	this.postals = this.arrayValue(_json.postals);
	this.events = this.arrayValue(_json.events);
	this.note = this.simpleValue(_json.note);

	this.getSimpleValue = function(_value) {
		if (_value.className == "empty" || _value.value == null
				|| _value.value.trim() == "") {
			return "";
		} else {
			return _value.value;
		}
	}
	this.getArrayValues = function(_values) {
		var values = new Array();
		var sources = _values.getElementsByTagName("input");
		for ( var i = 0; i < sources.length; i++) {
			var value = this.getSimpleValue(sources[i]);
			if (value != null) {
				values.push(value);
			}
		}
		return values;
	}
	this.getPredefinedValues = function(_select) {
		var values = new Array();
		for ( var i = 0; i < _select.options.length; i++) {
			var option = _select.options[i];
			if (option.selected) {
				values.push(option.textContent);
			}
		}
		return values;
	}
	this.getValuesJSON = function() {
		var result = new Object();
		result.name = this.getSimpleValue(this.name);
		result.nick = this.getSimpleValue(this.nick);
		result.groups = this.getPredefinedValues(this.groups);
		result.emails = this.getArrayValues(this.emails);
		result.phones = this.getArrayValues(this.phones);
		result.sips = this.getArrayValues(this.sips);
		result.postals = this.getArrayValues(this.postals);
		result.events = this.getArrayValues(this.events);
		result.note = this.getSimpleValue(this.note);
		return result;
	}
}
/*
 * Main "public" function
 */
function contacts_showDetails(_rawId) {
	contacts_detailsPopup = popup_showWait("contacts_" + _rawId);
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				addPing(new Date().getTime() - contactsReqSent);
				details = main_readJSONResponse(req);
				if(!details){
					return;
				}
				var detailsDiv = document.createElement("div");
				detailsDiv.appendChild(contacts_createRawDetails(details));
				contacts_detailsPopup = popup_show(details.name + " - "
						+ _T("Details"), detailsDiv, "contacts_" + _rawId);
			}
		}
	};
	main_encryptReq(req,"contactdetails",_rawId);
	contactsReqSent = new Date().getTime();
}

function contacts_createRawDetails(_json) {
	var rawDetails = new contacts_RawDetails(_json);
	contacts_rawDetailsSet[_json.idRaw] = rawDetails;
	var content = document.createElement("div");
	// alert(rawContact.deleted);
	if (rawDetails.deleted == "1") {
		content.textContent = _T("Deleted");
		return content;
	}
	var header = document.createElement("div");
	header.setAttribute("class", "contactHeader");
	header.appendChild(rawDetails.photo);
	header.appendChild(rawDetails.accountName);
	header.appendChild(rawDetails.accountType);
	content.appendChild(header);
	var table = document.createElement("table");
	table.appendChild(contacts_createValueRow(_T("Name"), rawDetails.name));
	table.appendChild(contacts_createValueRow(_T("Nick"), rawDetails.nick));
	table.appendChild(contacts_createValueRow(_T("Group"), rawDetails.groups));
	table.appendChild(contacts_createValueRow(_T("EMail"), rawDetails.emails));
	table.appendChild(contacts_createValueRow(_T("Phone"), rawDetails.phones));
	table.appendChild(contacts_createValueRow(_T("SIP"), rawDetails.sips));
	table.appendChild(contacts_createValueRow(_T("Postal"), rawDetails.postals));
	table.appendChild(contacts_createValueRow(_T("Events"), rawDetails.events));
	table.appendChild(contacts_createValueRow(_T("Note"), rawDetails.note));
	content.appendChild(table);
	// Toolbar
	var toolbar = document.createElement("div");
	toolbar.style.textAlign = "right";
	toolbar.appendChild(main_createButton(_T("Revert"), "contacts_showDetails('"
			+ rawDetails.rawId + "')"));
	toolbar.appendChild(main_createButton(_T("Save"), "contacts_save('"
			+ rawDetails.rawId + "')"));
	toolbar.appendChild(main_createButton(_T("Edit"), "contacts_edit('"
			+ rawDetails.rawId + "')"));
	toolbar.appendChild(main_createButton(_T("Delete"), "contacts_delete('"
			+ rawDetails.rawId + "')"));
	content.appendChild(toolbar);
	return content;
}

function contacts_createValueRow(_label, _value) {
	var tr = document.createElement("tr");
	tr.style.border = "none";
	var tdLabel = document.createElement("td");
	tdLabel.style.border = "none";
	var label = document.createElement("b");
	label.textContent = _label + ": ";
	tdLabel.appendChild(label);
	var tdValue = document.createElement("td");
	tdValue.style.border = "none";
	tdValue.appendChild(_value);
	tr.appendChild(tdLabel);
	tr.appendChild(tdValue);
	return tr;
}

/*
 * Start of interface functions
 */
function contacts_edit(_rawId) {
	contacts_rawDetailsSet[_rawId].setEditable();
}

function contacts_startEdit(_element) {
	if (_element.className = "empty" && _element.value == _T("Empty")) {
		_element.value = "";
	}
	_element.onkeypress = contacts_onKeyPress;
}

function contacts_stopEdit(_element) {
	if (_element.value.trim() == "") {
		_element.value = _T("Empty");
		_element.className = "empty";
	} else {
		_element.className = "";
	}
	_element.onkeypress = null;
}

function contacts_onKeyPress(_event) {
	var code = _event.keyCode;
	var source = _event.currentTarget;
	var rawDetails = source.rawDetails;
	switch (code) {
	case 13:
		if (source.isArrayValue) {
			var input = rawDetails.simpleValue("");
			source.parentNode.appendChild(input);
			rawDetails.setEditable();
		} else {
			return false;
		}
		break;
	default:
		return true;
	}
	return false;
}

/*
 * Operations
 */
function contacts_delete(_rawId) {
	contacts_doAction(_T("DoYouWantToDeleteTheContact"),"contactdelete",_rawId, _rawId);
}

function contacts_save(_rawId) {
	var rawDetails = contacts_rawDetailsSet[_rawId];
	var data=new Object();
	data.rawId=_rawId;
	data.data=rawDetails.getValuesJSON();
	contacts_doAction(_T("DoYouWantToSaveTheContactsDetails"),"contactupdate", data, _rawId);
}

function contacts_doAction(_message, _area, _data, _rawId) {
	contacts_confirmedData=new Object();
	contacts_confirmedData.area=_area;
	contacts_confirmedData.data=_data;
	contacts_confirmedData.rawId=_rawId;
	var content=document.createElement("div");
	content.textContent=_message;
	popup_showDialog(_T("Confirm"), content, "contacts_confirmedAction()", "");
}

function contacts_confirmedAction() {
	var rawId=contacts_confirmedData.rawId;
	popup_showWait("contacts_" + rawId);
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				addPing(new Date().getTime() - contactsReqSent);
				// contacts_showDetails(rawId);
				contacts_dirty = true;
				contacts_read();
				popup_hide("contacts_" + rawId);
			}
		}
	};
	main_scrollTop=document.documentElement.scrollTop;
	main_encryptReq(req,contacts_confirmedData.area,contacts_confirmedData.data);
	contactsReqSent = new Date().getTime();
}
